/**
 * Created with JetBrains WebStorm.
 * User: rekey
 * Date: 7/9/13
 * Time: 16:48
 * To change this template use File | Settings | File Templates.
 */
/** @namespace global.appPath */
var async = require('async');
var dao = require('../dao/index.js');
var page = require('../lib/page.js');

exports.index = function(req, res) {
    var slug = req.param('slug');
    var currentPage = req.param('page') || 1;

    var locals = {
        pageBaseUrl : '/category/' + slug + '/page/'
    };

    function getCategories(done) {
        dao.category.getList().then(function(categories) {
            done(null, categories);
        });
    }

    function getPostPages(done) {
        dao.post.getCountByCategorySlug(slug).then(function(count) {
            done(null, page.create(currentPage, count, 7));
        });
    }

    function getPosts(done) {
        dao.post.getListByCategorySlug(slug).then(function(posts) {
            done(null, posts);
        });
    }


    async.parallel({
        categories : getCategories,
        page : getPostPages,
        posts : getPosts
    }, function(err, results) {
        Object.keys(results).forEach(function(key) {
            locals[key] = results[key];
        });
        results.categories.forEach(function(category) {
            if (category.slug == slug) {
                locals.category = category;
            }
        });
        res.render('pages/category', {data:locals});
    });

};
exports.create = function(req, res) {
    if (req.method == 'GET') {
        dao.category.getList().then(function(categories) {
            res.render('category-add', {
                'title' : 'Express',
                'categories' : categories,
                'currentCategory' : 'index'
            });
        });
    } else {
        dao.category.create(req.body).then(function(doc) {
            res.json(doc);
        });
    }
};